package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver = null;
    public static String DetailUrl = "http://127.0.0.1:58080/sign-in.html";
    public WebDriverWait wait = null;

    public Utils (String url) {
        // 调用 driver 对象
        driver = createWebDriver();
        DetailUrl = url;
        wait = new WebDriverWait(driver,Duration.ofSeconds(2));
        driver.get(DetailUrl);
    }

    /**
     * 获得驱动对象
     * @return 驱动对象
     */
    public static WebDriver createWebDriver() {
        if (driver == null) {
            // 下载驱动
            WebDriverManager.chromedriver().setup();
            ChromeOptions options = new ChromeOptions();
            // 设置窗口大小（例如 1920x1080）
            options.addArguments("window-size=1400,1000");
            // 允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
             // 无头模式
            options.addArguments("--headless");

            driver = new ChromeDriver(options);
        }
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        return driver;
    }

    public static void ScreenShot (String str) throws IOException {
        //屏幕截图文件目录
        //   ./src/test/java/images/
        //                         /2025-03-02/
        //                                    /test01_09372010.png
        //                                    /test02_09372011.png
        //                         /2025-03-03/
        //                                    /test01_19372010.png
        //                                    /test02_19372011.png

        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");
        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());
        //./src/test/java/images/2025-03-02/test01_13972011.png
        String fileName = "./src/test/java/images/" + dirTime + "/" + str
                + "-" + fileTime + ".png";
        File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(srcFile,new File(fileName));
    }
}
